#include "mk_utility.h"

#include <stdlib.h>
#include <memory.h>
#include <string.h>

mk_utility::mk_utility()
{

}

mk_utility::~mk_utility()
{

}

void mk_utility::reverse_bytes( void * input, long len )
{
	unsigned char swap;
	long i;
	unsigned char * pTmp = (unsigned char*)input;

	for (i=0; i<len/2; i++)
	{
		swap = pTmp[i];
		pTmp[i] = pTmp[len-i-1];
		pTmp[len-i-1] = swap;
	}
}

void mk_utility::fill_buff_with_word_value_be( unsigned short wValue, unsigned char * buff) 
{
	unsigned char data[2] = {0};
	memcpy(data, &wValue, 2);
	mk_utility::reverse_bytes(data,2);

	memcpy(buff, data, 2);
}

void mk_utility::fill_buff_with_dword_value_be( unsigned long dwValue, unsigned char * buff )
{
	unsigned char data[4] = {0};
	memcpy(data, &dwValue, 4);
	mk_utility::reverse_bytes(data,4);

	memcpy(buff, data, 4);
}


unsigned long mk_utility::reverse_dword(unsigned long InData)
{
	unsigned long      dwRet = 0;
	unsigned char*     const     pRet = (unsigned char*)&dwRet;
	unsigned char*     const     pInData = (unsigned char*)&InData;

	pRet[3] = pInData[0];
	pRet[2] = pInData[1];
	pRet[1] = pInData[2];
	pRet[0] = pInData[3];

	return dwRet;
}

unsigned short mk_utility::reverse_word(unsigned short InData)
{
	unsigned  short     wRet = 0;
	unsigned  char *    const     pRet = (unsigned char *)&wRet;

	unsigned char *  const     pInData = (unsigned char*)&InData;
	pRet[1] = pInData[0];
	pRet[0] = pInData[1];

	return wRet;
}

int mk_utility::split_strings(char * delim, char * input, char strArrays[32][256])
{
	char temp[4096] = {0};
	char * p = NULL;
	int  num = 0;
	strncpy(temp, input, 4096);

	p = strtok(temp, delim);
	if(!p) return -1;

	strncpy(strArrays[num++], p, 256);

	while(p = strtok(NULL, delim))
	{
		strncpy(strArrays[num++], p, 256);
		if(num >= 32)
		{
			break;
		}
	}

	return num;
}


int mk_utility::ascii_to_unicode( char * asciiStr, unsigned short * unicodeStr, int * uniStrInBytes )
{
	int iLen = strlen(asciiStr);

	if((iLen + 1 ) * 2 > *uniStrInBytes)
	{
		return 1;
	}

	for(int i = 0 ; i < iLen ; i ++)
	{
		unicodeStr[i] = asciiStr[i];
	}

	* uniStrInBytes = iLen * 2;
	return 0;
}

void mk_utility::ltrim ( char *s )
{
	char *p;
	p = s;
	while ( *p == ' ' || *p == '\t' ) {*p++;}
	strcpy ( s,p );
}

void mk_utility::rtrim ( char *s )
{
	int i;

	i = strlen ( s )-1;
	while ( ( s[i] == ' ' || s[i] == '\t' ) && i >= 0 ) {i--;};
	s[i+1] = '\0';
}

void mk_utility::trim ( char *s )
{
	ltrim ( s );
	rtrim ( s );
}
